import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '@/store'
import qs from 'qs'

// const BASE_URI = process.env.NODE_ENV === 'production' ? window.location.origin +'/xxx/' : process.env.BASE_API
// create an axios instance
const service = axios.create({
    baseURL: process.env.BASE_API,
    timeout: process.env.TIME_OUT
})

// request interceptor
service.interceptors.request.use(
    config => {
        // Do something before request is sent
        if (store.getters.token) {
            // config.headers['X-Token'] = getToken()
        }
        if (config.data && !(config.data instanceof FormData)) {
            config.data = config.data ? qs.stringify(config.data) : ''
        }
        config.withCredentials = true
        // config.url = config.url + '.action'
        return config
    },
    error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

function processProjectConfigChange(res) {
    // if (res.projectConfigRecord && res.projectConfigRecord.length > 0) {
    //     localStorage.setItem('projectConfigChange', JSON.stringify(res.projectConfigRecord))
    // }else{
    //     localStorage.removeItem('projectConfigChange')
    // }
}

// response interceptor
service.interceptors.response.use(
    response => {
        const contentType = response.headers['content-type']
        if (!contentType) {
            return null
        } else if (contentType.indexOf('json') === -1) {
            if (contentType.indexOf("noautodownload") !== -1) {
                //标注不要自动下载文件
                return response
            }
            // 下载处理
            const filename = response.headers['content-disposition']
            const isdownload = contentType.indexOf('download') !== -1 || contentType.indexOf('ms-excel') !== -1 ||
                contentType.indexOf('octet-stream') !== -1 || contentType.indexOf('force-download') !== -1
            if (filename || isdownload) {
                let fn = decodeURIComponent(filename.split('filename=')[1])
                const blob = new Blob([response.data])
                if (window.navigator.msSaveOrOpenBlob) {
                    // 兼容ie
                    window.navigator.msSaveBlob(blob, fn)
                } else {
                    var downloadElement = document.createElement('a')
                    var href = window.URL.createObjectURL(blob)
                    downloadElement.href = href
                    downloadElement.download = fn
                    document.body.appendChild(downloadElement)
                    // 此写法兼容火狐
                    let evt = document.createEvent('MouseEvents')
                    evt.initEvent('click', false, false)
                    downloadElement.dispatchEvent(evt)
                    document.body.removeChild(downloadElement)
                    window.URL.revokeObjectURL(href)
                }
            } else {
                return response
            }
        } else {
            // json格式的返回类型才走下面的步骤
            let res = response.data
            var isBlob = res instanceof Blob
            if (isBlob) {
                var reader = new FileReader()
                reader.addEventListener('loadend', function (e) {
                    var json = e.target.result
                    res = JSON.parse(json)
                    if (res.status !== true) {
                        Message({
                            message: res.message,
                            type: 'error',
                            duration: 5 * 1000
                        })
                        // 401:Token过期 或 未登录
                        if (res.code == '401') {
                            // 请自行在引入 MessageBox
                            // import { Message, MessageBox } from 'element-ui'
                            MessageBox.confirm('你已被登出，是否重新登录？', '提示', {
                                confirmButtonText: '重新登录',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => {
                                store.dispatch('FedLogOut').then(() => {
                                    location.reload() // 为了重新实例化vue-router对象 避免bug
                                })
                            })
                        }
                        // eslint-disable-next-line prefer-promise-reject-errors
                        return Promise.reject('error')
                    } else {
                        processProjectConfigChange(response.data)
                        return response.data
                    }
                })
                reader.readAsText(res)
            } else {
                if (res.status !== true) {
                    Message({
                        message: res.message,
                        type: 'error',
                        duration: 5 * 1000
                    })

                    // 402手动登出
                    if (res.code == '402') {
                        store.dispatch('FedLogOut').then(() => {
                            location.reload()
                        })
                    } else if (res.code == '401') {
                        // 401:Token过期 或 未登录
                        MessageBox.confirm('你已被登出，是否重新登录？', '提示', {
                            confirmButtonText: '重新登录',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            store.dispatch('FedLogOut').then(() => {
                                location.reload() // 为了重新实例化vue-router对象 避免bug
                            })
                        })
                    }
                    // eslint-disable-next-line prefer-promise-reject-errors
                    return Promise.reject('error')
                } else {
                    processProjectConfigChange(response.data)
                    return response.data
                }
            }
        }
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
